# Install Java 21 LTS
Write-Host "Installing Java 21 LTS..." -ForegroundColor Green

# Download URL for Java 21
$downloadUrl = "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4%2B7/OpenJDK21U-jdk_x64_windows_hotspot_21.0.4_7.zip"
$zipPath = "$env:TEMP\openjdk-21.zip"
$installDir = "C:\Program Files\Eclipse Adoptium\jdk-21.0.4.7-hotspot"

Write-Host "Downloading Java 21..." -ForegroundColor Yellow
try {
    Invoke-WebRequest -Uri $downloadUrl -OutFile $zipPath -UseBasicParsing
    Write-Host "Download completed" -ForegroundColor Green
} catch {
    Write-Host "Download failed: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "Please manually download Java 21 from: https://adoptium.net/temurin/releases/?version=21" -ForegroundColor Yellow
    exit 1
}

# Create installation directory
Write-Host "Creating installation directory..." -ForegroundColor Yellow
if (!(Test-Path "C:\Program Files\Eclipse Adoptium\")) {
    New-Item -ItemType Directory -Path "C:\Program Files\Eclipse Adoptium\" -Force
}

# Extract
Write-Host "Extracting Java 21..." -ForegroundColor Yellow
try {
    Expand-Archive -Path $zipPath -DestinationPath "C:\Program Files\Eclipse Adoptium\" -Force
    
    # Find extracted folder and rename
    $extractedFolder = Get-ChildItem "C:\Program Files\Eclipse Adoptium\" | Where-Object { $_.Name -like "jdk-21*" -and $_.Name -notlike "*hotspot" } | Select-Object -First 1
    if ($extractedFolder) {
        if (Test-Path $installDir) {
            Remove-Item $installDir -Recurse -Force
        }
        Rename-Item $extractedFolder.FullName $installDir -Force
    }
    
    Write-Host "Java 21 installation completed" -ForegroundColor Green
} catch {
    Write-Host "Extraction failed: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# Set environment variables
Write-Host "Setting environment variables..." -ForegroundColor Yellow
[Environment]::SetEnvironmentVariable("JAVA_HOME", $installDir, "User")

# Update PATH
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
$javaBin = "$installDir\bin"
$pathArray = $currentPath -split ";" | Where-Object { $_ -notlike "*jdk*\bin" -and $_ -notlike "*java*\bin" }
$newPath = ($javaBin, $pathArray) -join ";"
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")

# Refresh current session
$env:JAVA_HOME = $installDir
$env:Path = "$javaBin;$env:Path"

Write-Host "Environment variables set" -ForegroundColor Green
Write-Host "JAVA_HOME: $installDir" -ForegroundColor Cyan

# Verify installation
Write-Host "Verifying installation..." -ForegroundColor Yellow
try {
    & "$javaBin\java.exe" -version
    Write-Host "Java 21 installed successfully!" -ForegroundColor Green
} catch {
    Write-Host "Verification failed, please restart PowerShell" -ForegroundColor Yellow
}

# Cleanup
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue

Write-Host "Installation completed! Please restart PowerShell or IDE" -ForegroundColor Green